# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/1/20 17:27
# @Author  : qiaoc
# @File    : AffixUtils.py
# @Desc    : 附件处理
import os
import zipfile
import rarfile
import shutil

from PyPDF2 import PdfFileReader,PdfFileWriter
from dao.PyMysql import *
import pandas as pandas

all_filename = []


# 整理固化类型的附件，返回顺序正确的文件路径列表，压缩文件则解压缩
def get_curing_ocr_attachment(floder_path):
    try:
        result_att = []

        new_all_file = []
        same_floder = []
        rar_file = []
        for i in range(1,7):
            new_floder_path = floder_path + '\附件' + str(i)
            all_file = os.listdir(new_floder_path)
            for f in all_file:
                if f in same_floder:
                    continue
                if '.png' in str(f) or '.jpeg' in str(f) or '.jpg' in str(f) or '.bmp' in str(f) or '.pdf' in str(f):
                    new_all_file.append([str(f), new_floder_path + r"\\" + str(f)])
                    continue
                # if '.pdf' in str(f):
                #     split_pdf(new_floder_path + r"\\" + str(f))
                #     new_split_path = new_floder_path + r"\\" + str(f).replace('.pdf', '')
                #     if os.path.isdir(new_split_path):
                #         if '.pdf' in new_split_path:
                #             new_all_file.append([str(f), new_split_path])
                #         next_all_file = os.listdir(new_split_path)
                #         for next_f in next_all_file:
                #             if '.png' in str(next_f) or '.jpeg' in str(next_f) or '.pdf' in str(next_f) or '.jpg' in str(next_f) or '.bmp' in str(next_f):
                #                 new_all_file.append([str(f), new_split_path + r"\\" + str(next_f)])
                #                 continue
                #     continue
                if 'zip' == str(f).split('.')[-1]:
                    # print('zip file')
                    unzipFloder = unzip_zip_file(new_floder_path + r"\\" + str(f))
                    same_floder.append(unzipFloder)
                    # unzip_files = os.listdir(unzipFloder)
                    # global all_filename
                    all_filename = get_all_filename(unzipFloder)
                    for uz in all_filename:
                        new_all_file.append([str(f), uz])
                    # print(new_all_file)
                if 'rar' == str(f).split('.')[-1]:
                    unrarFloder = unrar_rar_file(new_floder_path + r"\\" + str(f))
                    same_floder.append(unrarFloder)
                    # unzip_files = os.listdir(unzipFloder)
                    # global all_filename
                    # all_filename = []
                    all_filename = get_all_filename(unrarFloder)
                    for uz in all_filename:
                        new_all_file.append([str(f), uz])
                    # if '附件1' in f:
                    #     rar_file.append('附件1')
                    # if '附件2' in f:
                    #     rar_file.append('附件2')
                    # if '附件3' in f:
                    #     rar_file.append('附件3')
                    # if '附件4' in f:
                    #     rar_file.append('附件4')
                    # if '附件5' in f:
                    #     rar_file.append('附件5')
                    # if '附件6' in f:
                    #     rar_file.append('附件6')

                if 'doc' == str(f).split('.')[-1]:
                    if '附件1' in f:
                        rar_file.append('附件1')
                    if '附件2' in f:
                        rar_file.append('附件2')
        return new_all_file, rar_file
    except Exception as e:
        # print(e, e.__traceback__.tb_lineno)
        pass


def unzip_zip_file(file_name):
    """unzip zip file ---- return new floder path"""
    zip_file = zipfile.ZipFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    for names in zip_file.namelist():
        zip_file.extract(names, file_name + "_files/")
    zip_file.close()
    flodp = file_name + "_files"
    change_file_name(flodp)
    for j in os.listdir(flodp):
        if '.zip' in str(j):
            unzip_zip_file(flodp + r'/' + j)
    return flodp

def unrar_rar_file(file_name):
    rar_file= rarfile.RarFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    for names in rar_file.namelist():
        rar_file.extract(names, file_name + "_files/")
    rar_file.close()
    flodp = file_name + "_files"
    change_file_name(flodp)
    for j in os.listdir(flodp):
        if '.rar' in str(j):
            unrar_rar_file(flodp + r'/' + j)
    return flodp


def change_file_name(filename):
    os.chdir(filename)
    for i in os.listdir(filename):
        try:
            test_name = i.encode("cp437")
            test_name = test_name.decode("gbk")  # 将文件名转为gbk中文编码
            os.rename(i, test_name)  # 重命名
            i = test_name
        except:
            pass
        if os.path.isdir(i):  # 如果解压后的是一个文件夹
            change_file_name(filename + r'/' + i)
            os.chdir('..')


def unzip_rar_file(file_name):
    """unzip rar file  ---- return new floder path"""
    # rar = rarfile.RarFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    # os.chdir(file_name + "_files")
    # rar.extractall()
    # rar.close()
    return file_name + "_files"

def get_all_filename(path):
    dir_list = os.listdir(path)
    # if len(dir_list) == 1 and '.' not in dir_list[0]:
    #     dir_list = os.listdir(path + '\\' + dir_list[0])
    for i in dir_list:
        sub_dir = os.path.join(path, i)
        if os.path.isdir(sub_dir):
            get_all_filename(sub_dir)
        else:
            i = i.lower()
            if '.png' in str(i) or '.jpeg' in str(i) or '.pdf' in str(i) or '.jpg' in str(i) or '.bmp' in str(i):
                all_filename.append(sub_dir)
    return all_filename
def get_affix_url_with_name(affix_list, name):
    url = ''
    for a in affix_list:
        if str(name) in str(a):
            return affix_list[a]
    return url

# 从数据库的附件表查询缴费单对应的附件
def get_affix_from_db(bill_number):
    affix_db = {}
    affix_db_tablename = 'nf_affix_info'
    affix_db_sql = """SELECT * FROM """ + affix_db_tablename + """ WHERE code='""" + bill_number + """' and recycle_id = '0' """
    affix_list = PyMysql().get_db_data(affix_db_sql)
    if affix_list and len(affix_list) > 0:
        for a in affix_list:
            affix_db[a['name']] = a['url']
    return affix_db

# 得到所有附件名（附件1-5）
def get_all_attachment(floder_path):
    result_files = {'附件1': '', '附件2': '', '附件3': '', '附件4': '', '附件5': '', '附件6': ''}
    for i in range(1, 7):
        new_floder_path = floder_path + '\附件' + str(i)
        all_file = os.listdir(new_floder_path)
        for f in all_file:
            # print(f)
            if 'files' in str(f):
                continue
            for r in result_files:
                if str(r) in f:
                    result_files[str(r)] = f
    return result_files


# 文件分类，创建六个文件夹，把对应的附件放到对应的文件夹中，譬如：附件1放进附件1文件夹，该方法解决附件1-xxx1，附件1-xxx2等同个附件多个文件情况
def file_classification(floder_path):
    all_file_name = os.listdir(floder_path)
    for i in range(1, 7):
        file = floder_path + '//' + '附件' + str(i)
        if not os.path.exists(file):
            os.makedirs(file)
    # print(all_file_name)
    for name in all_file_name:
        if ('附件1' in name or '附件一' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件1//' + name
            shutil.move(old_path, new_oath)
        elif ('附件2' in name or '附件二' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件2//' + name
            shutil.move(old_path, new_oath)
        elif ('附件3' in name or '附件三' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件3//' + name
            shutil.move(old_path, new_oath)
        elif ('附件4' in name or '附件四' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件4//' + name
            shutil.move(old_path, new_oath)
        elif ('附件5' in name or '附件五' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件5//' + name
            shutil.move(old_path, new_oath)
        elif ('附件6' in name or '附件六' in name) and '.' in name:
            old_path = floder_path + '//' + name
            new_oath = floder_path + '//附件6//' + name
            shutil.move(old_path, new_oath)


# PDF文件分割，有部分pdf附件存在多页情况，ocr识别只能识别第一页内容，先凡是pdf文件无论是1页或者多页都会拆分为一页一文件
def split_pdf(read_file):
    try:
        fp_read_file = open(read_file, 'rb')
        pdf_input = PdfFileReader(fp_read_file)  # 将要分割的PDF内容格式话
        page_count = pdf_input.getNumPages()  # 获取PDF页数
        # print(page_count)  # 打印页数

        write_file = read_file.replace('.pdf','')
        # print(write_file)
        if not os.path.exists(write_file):
            os.mkdir(write_file)
        split = True
        for i in range(page_count):
            pdf_file = write_file + '\\' + str(i+1) + '.pdf'
            start_page = i
            end_page = i + 1
            try:
                # print(f'开始分割第{end_page}页，保存为{pdf_file}......')
                pdf_output = PdfFileWriter()  # 实例一个 PDF文件编写器
                for i in range(start_page, end_page):
                    pdf_output.addPage(pdf_input.getPage(i))
                with open(pdf_file, 'wb') as sub_fp:
                    pdf_output.write(sub_fp)
                # print(f'完成分割第{end_page}页，保存为{pdf_file}!')
            except IndexError:
                split = False
                # print('分割页数超过了PDF的页数')
        return write_file
        pass
    except Exception as e:
        split = False
        # print(e)
    finally:
        fp_read_file.close()
        if split:
            os.remove(read_file)

# excel表格类型
def excel_to_data(path, filename):
    try:
        # print('excel表格类型')
        excel_data = pandas.read_excel(path, usecols=[1, 2, 3, 4, 5, 6, 7, 8, 9])
        excel_data['附件名'] = filename
        excel_data.fillna('', inplace=True)
        data_list = excel_data.values.tolist()
        # print(data_list[0])
        if data_list[0] == ['所属区县', '报账点编码', '报账点名称', '站址编码', '户号', '超标类型', '超标原因', '新增4G情况', '新增5G情况', filename]:
            data_list = data_list[1:]
            # print(data_list)
            key = ['district', 're_code', 're_name', 'site_code', 'door_no', 'standard_type', 'standard_because',
                   'new_4g_case',
                   'new_5g_case', 'affixx_name']
            PyMysql().insert_data('rpa_standard_site', key, data_list)
            return True
    except Exception as e:
         # print(e, ' ', e.__traceback__.tb_lineno)
         pass
